// 新建一个对象]
(function(window,config,$api) {
	var r = function(){
		this.init();
	}

	r.prototype.init = function(){
		this.url=null;
		this.urlParams=null;
		this.method=null;
		this.data=[];
	}
	r.prototype.constructor = r;
	r.prototype.rulers = config.restRoute;
	// 拼接url
	r.prototype.generateUrl = function(name,parameter){
		if(this.rulers[name] != undefined){
			var url = config.apiHost+this.rulers[name];
			if(typeof parameter === 'object'){
				for(i in parameter){
					var re = new RegExp('\{'+i+'\}');
					url = url.replace(re,parameter[i]);
				}
				url = url.replace(/\{\w+\}/g,'');
			}else if(parameter === undefined){
				url = url.replace(/\{\w+\}/g,'');
			}else{
				url = url.replace(/\{\w+\}/,parameter);
			}
			return url.replace(/\/*$/,'');
		}else{
			return name;
		}
	}

	r.prototype.parameter = function(params){
		this.urlParams=params;
		return this;
	}
	// get方法
	r.prototype.get= function(url,parameter){
		this.url= this.generateUrl(url,parameter);
		this.method='GET';
		return this;
	}
	// post方法
	r.prototype.post= function(url,parameter){

		this.url= this.generateUrl(url,parameter);
		this.method='POST';
		return this;
	}
	r.prototype.datae = function(values){
		this.data= values;
		return this;
	}
	r.prototype.datae2 = function(values){
		this.data= values;
		return this;
	}
	r.prototype.setAuthPrefs = function(ret){
		api.writeFile({
			path: 'fs://hengxing/auth.json',
			data: JSON.stringify(ret)
		}, function(ret, err) {

		});
	}
	r.prototype.removeAuthPrefs = function(){
		api.writeFile({
			path: 'fs://hengxing/auth.json',
			data: ''
		}, function(ret, err) {

		});
	}
	r.prototype.linkUrlWithParams = function(){
		if(this.urlParams != null){
			this.url = this.url.replace(/\?$/,'')+'&';
			for(i in this.urlParams){
				this.url += i+'='+this.urlParams[i]+'&';
			}
			this.url = this.url.replace(/\&$/,'');
		}
		return this;
	}

	r.prototype.success = function(fn) {
		this.su = fn;
		return this;
	};

	r.prototype.error = function(fn) {
		this.er = fn;
		return this;
	};
	r.prototype.allurl=function(url,params) {
			if (typeof params== "object") {
					var url2='';
					for (var i in params) {
							url2 +=i+'/'+params[i]+'/';
					}
			}
			return url+'/'+url2
	}
	r.prototype.run = function(){
		if(this.urlParams != null){
			this.linkUrlWithParams();
		}
		var obj = this;
		console.log(this.allurl(this.url,this.data))

		api.ajax({
			url: obj.url,
			method: obj.method,
			dataType:'json',
			cache:true,
			data:{
					values: obj.data,
        	files: obj.data,
			}
		,
		}, function(ret, err) {
			if (ret) {
				if(ret.msg=='登录已过期或凭证错误'){
					$api.rmStorage('uid');
					$api.rmStorage('session');
				}else{
					obj.su(ret);
				}
			} else {
				obj.er(err);
			}
		});
	}
  window.rest = r;
})(window,config,$api)
